package com.kristin.letcode.lengthOfLongestSubstring;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

// letCode题目：获取一串字符串中不重复的最长的字符
public class Solution {

    public static void main(String[] args) {
        System.out.println(Solution2("dvdf"));
    }

    public static int Solution1(String s) {
        char[] chars = s.toCharArray();
        int left = 0;
        int right = 0;
        int lengthOfLongest = 0;
        while (left < chars.length) {
            Set<Character> sets = new HashSet<>();
            right = left;
            while (right < chars.length) {
                if (sets.contains(chars[right])) {
                    break;
                }
                sets.add(chars[right]);
                right++;
            }
            left++;
            lengthOfLongest = lengthOfLongest > sets.size() ? lengthOfLongest : sets.size();
        }
        return lengthOfLongest;
    }

    public static int Solution2(String s) {
        int left = 0;
        int longOfLongest = 0;
        Map<Character, Integer> mp = new HashMap<>();
        int temp = 0;
        while(left < s.length()) {
            char c = s.charAt(left);
            // 如果字符
            if(mp.containsKey(c)) {
                // 字符重复了，重复字符索引+1 继续循环
                left = mp.get(c) + 1;
                mp.clear();
                longOfLongest = Math.max(longOfLongest, temp);
                temp = 0;
                continue;
            }
            temp++;
            longOfLongest = Math.max(longOfLongest, temp);
            mp.put(c, left);
            left++;
        }
        return longOfLongest;
    }

}
